﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;

using DotSpatial.Controls;
using DotSpatial.Symbology;
using DotSpatial.Data;
using DotSpatial.Topology;

using System.Drawing;

using Point = System.Drawing.Point;


namespace HAGISV2
{







    /// <summary>
    /// 小刘写
    /// </summary>
    public class HGMSSelectMF : HMapFunction
    {

        # region 需求分析

        // 1 框选和点选统一，都是复选
        // 2 端点是指图形的首尾点。顶点则是非端点。
        // 3 端点选择和顶点选择是分开状态，哪怕一个端点和一个顶点重合，在各自的选择模式下选各自的。
        // 4 在全选模式下,框选和点选是两种点都选，且是优先选，再选线，最后选面。（主要用于多边形线转多边形的情况）
        // 5 右键菜单设置坐标时，如果在同一位置选择了n个点（可同时包括端点和顶点），是可以设置的。如果同时选择了不同位置的端点和顶点，则是不可设置的。
        //   同一位置时判断可设置坐标后，再判断是顶点还是端点，端点具有优先级
        // 6 多边形线转换多边形后，将多边形线切成两条再合并，如何与所转的多边形进行对应？？？？？同理，当给一个多边形线插入顶点后如何与多边形进行对应？？？


        # endregion


        public HGMSSelectMF(IMap map)
            : base(map)
        {
        }

        //这个方法既有点选又有框选
        //


        # region 选择机制字段

        private HSelectMode _selectMode = HSelectMode.None;

        # endregion

        # region 选择机制设置

        /// <summary>
        /// 设置选择方式
        /// </summary>
        /// <param name="mode"></param>
        public void SetSelectMode(HSelectMode mode)
        {
            this._selectMode = mode;
        }


        # endregion





        private List<IFeatureLayer> layerLst
        {
            get
            {
                if (this.InteractiveSystem.CurrentLayer == null)
                {
                    return new List<IFeatureLayer>();
                }
                VectorLayer layer = this.InteractiveSystem.CurrentLayer as VectorLayer;
                if (layer == null)
                {
                    return new List<IFeatureLayer>();
                }

                List<IFeatureLayer> layLst = new List<IFeatureLayer>();

                DotSpatial.Symbology.IFeatureLayer ptFeatureLayer = layer.PtLayer as DotSpatial.Symbology.IFeatureLayer;
                if (ptFeatureLayer != null)
                {
                    layLst.Add(ptFeatureLayer);
                }

                DotSpatial.Symbology.IFeatureLayer lnFeatureLayer = layer.LnLayer as DotSpatial.Symbology.IFeatureLayer;
                if (lnFeatureLayer != null)
                {
                    layLst.Add(lnFeatureLayer);
                }

                DotSpatial.Symbology.IFeatureLayer polyFeatureLayer = layer.PyLayer as DotSpatial.Symbology.IFeatureLayer;
                if (polyFeatureLayer != null)
                {
                    layLst.Add(polyFeatureLayer);
                }

                return layLst;

            }
        }

        //下面四个字段是将图形分离出来单存

        List<VectorShape> PointShps
        {
            get
            {
                if (this.InteractiveSystem.CurrentLayer == null) return new List<VectorShape>();
                VectorLayer vectorLyaer = this.InteractiveSystem.CurrentLayer as VectorLayer;
                if (vectorLyaer == null) return new List<VectorShape>();

                return vectorLyaer.Shapes.FindAll(h => (h as PointShape) != null);

            }
        }

        List<VectorShape> NodeShps
        {
            get
            {
                if (this.InteractiveSystem.CurrentLayer == null) return new List<VectorShape>();
                VectorLayer vectorLyaer = this.InteractiveSystem.CurrentLayer as VectorLayer;
                if (vectorLyaer == null) return new List<VectorShape>();

                return vectorLyaer.Shapes.FindAll(h => (h as NodeShape) != null);

            }
        }

        List<VectorShape> LineShps
        {
            get
            {
                if (this.InteractiveSystem.CurrentLayer == null) return new List<VectorShape>();
                VectorLayer vectorLyaer = this.InteractiveSystem.CurrentLayer as VectorLayer;
                if (vectorLyaer == null) return new List<VectorShape>();

                return vectorLyaer.Shapes.FindAll(h => (h as LineShape) != null);

            }
        }

        List<VectorShape> PolygonShps
        {
            get
            {
                if (this.InteractiveSystem.CurrentLayer == null) return new List<VectorShape>();
                VectorLayer vectorLyaer = this.InteractiveSystem.CurrentLayer as VectorLayer;
                if (vectorLyaer == null) return new List<VectorShape>();

                return vectorLyaer.Shapes.FindAll(h => (h as PolyShape) != null);

            }
        }



        # region 暴露给外部只读属性

        private List<PointShape> _selectedPts;

        public List<PointShape> SelectedPtShps
        {
            get { return _selectedPts; }
        }

        private List<NodeShape> _selectedNodes;

        public List<NodeShape> SelectedNodes
        {
            get { return _selectedNodes; }
        }

        private Dictionary<LineShape, List<int>> _selectedVertexs;

        public Dictionary<LineShape, List<int>> SelectedVertexs
        {
            get { return _selectedVertexs; }
        }

        private List<LineShape> _selectedLines;

        public List<LineShape> SelectedLines
        {
            get { return _selectedLines; }
        }

        private List<PolyShape> _selectedPolyons;

        public List<PolyShape> SelectedPolyons
        {
            get { return _selectedPolyons; }
        }


        private Dictionary<string, int> _rightSelectShp;

        public Dictionary<string, int> RightSelectShp
        {
            get { return _rightSelectShp; }
            set { _rightSelectShp = value; }
        }


        
        private CONCEPTLAYERRIGHTMENU _type;

        /// <summary>
        /// 哪种图形右键菜单
        /// </summary>
        public CONCEPTLAYERRIGHTMENU Type
        {
            get { return _type; }
        }

        # endregion


        private Point _mousePosition;

        //下面三个框选的字段，原以为只有点选呢……
        private bool _selecting = false;  //用于MouseDown时……
        private Point _startPosition;
        private Point _endPosition;
        private bool _isClick = false;  //是点选为true,是框选为false

        private bool _selected = false; //这个字段主要是用来判断是否选择了，用于全选模式时优先选择是否选择了的判断

        //复选字段
        private bool _check = false;

        //下面是关于移动的字段
        private bool _dragging = false;
        private List<Coordinate> _nextPoints = null;
        private Coordinate _dragPoint = null;
        private VectorShape _dragShp = null;
        private int _dragIndex = 0;

        private Coordinate _startDragPoint = null;

        # region 要暴露给外部的颜色可写属性

        SolidBrush _nodeBrush = new SolidBrush(Color.Red);

        public SolidBrush NodeBrush
        {
            get { return _nodeBrush; }
            set { _nodeBrush = value; }
        }

        float _nodeSize = 5.0f;

        public float NodeSize
        {
            get { return _nodeSize; }
            set { _nodeSize = value; }
        }


        SolidBrush _pointBrush = new SolidBrush(Color.Red);

        public SolidBrush PointBrush
        {
            get { return _pointBrush; }
            set { _pointBrush = value; }
        }

        float _pointSize = 3.0f;

        public float PointSize
        {
            get { return _pointSize; }
            set { _pointSize = value; }
        }




        Pen _linePen = new Pen(Color.Red, 2.0f);

        public Pen LinePen
        {
            get { return _linePen; }
            set { _linePen = value; }
        }

        SolidBrush _polygonBrush = new SolidBrush(Color.Blue);

        public SolidBrush PolygonBrush
        {
            get { return _polygonBrush; }
            set { _polygonBrush = value; }
        }


        # endregion


        ContextMenuStrip _context;


        # region 继承的方法

        protected override void OnActivate()
        {
            //this.layerLst = LayerLst;
            this._selectedPts = new List<PointShape>();
            this._selectedNodes = new List<NodeShape>();
            this._selectedVertexs = new Dictionary<LineShape, List<int>>();
            this._selectedLines = new List<LineShape>();
            this._selectedPolyons = new List<PolyShape>();

            this._startDragPoint = new Coordinate();

            this._rightSelectShp = new Dictionary<string, int>();

            base.OnActivate();
        }

        protected override void OnDeactivate()
        {
            base.OnDeactivate();

            this._selecting = false;

            this._selectedPts = null;
            this._selectedNodes = null;
            this._selectedVertexs = null;
            this._selectedLines = null;
            this._selectedPolyons = null;

            this._nextPoints = null;
            this._dragging = false;
            this._dragPoint = null;

            this._rightSelectShp = new Dictionary<string, int>();

            //保注释  减少不必要的刷新
            //刘加，这个刷新是必须有的
            //Map.MapFrame.Initialize();
            Map.Invalidate();
        }


        protected override void OnDraw(MapDrawArgs e)
        {
            VectorLayer layer = this.InteractiveSystem.CurrentLayer as VectorLayer;
            if (layer == null) return;
            if (layer.Visible == false || layer.ViewMode != FMAPVIEW.NORMAL) return;

            if (this._standBy)
            {
                return;
            }
            try
            {
                e.Graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;

                this.DisplayFeature(e);

                if (this._selecting == true) // && this._isClick == false)
                {
                    e.Graphics.DrawRectangle(Pens.Black, new Rectangle(Math.Min(this._startPosition.X, this._mousePosition.X), Math.Min(this._startPosition.Y, this._mousePosition.Y),
                        Math.Abs(this._mousePosition.X - this._startPosition.X), Math.Abs(this._startPosition.Y - this._mousePosition.Y)));
                    //Map.MapFrame.Initialize();
                    //Map.Invalidate();
                    //return;
                }

                if (this._dragging == true)
                {

                    Rectangle rect = new Rectangle(this._mousePosition.X - 3, this._mousePosition.Y - 3, 6, 6);

                    IEnvelope env = this.Map.PixelToProj(rect).ToEnvelope();

                    if (env.Contains(this._startDragPoint) == false)
                    {

                        e.Graphics.FillEllipse(this._pointBrush, this._mousePosition.X - 5, this._mousePosition.Y - 5, 10.0f, 10.0f);

                        if (this._nextPoints != null && this._nextPoints.Count > 0)
                        {
                            foreach (Coordinate c in this._nextPoints)
                            {
                                e.Graphics.DrawLine(this._linePen, this.Map.ProjToPixel(c), this._mousePosition);
                            }
                        }
                        //Map.MapFrame.Initialize();
                        //Map.Invalidate();
                        //return;
                    }
                }

                if (this._selectedPts != null)
                {
                    foreach (PointShape point in this._selectedPts)
                    {
                        Point pt = Map.ProjToPixel(point.Geometry.Coordinates[0]);
                        e.Graphics.FillEllipse(this._nodeBrush, pt.X - this._nodeSize, pt.Y - this._nodeSize, this._nodeSize * 2, this._nodeSize * 2);
                    }
                }

                if (this._selectedNodes != null)
                {
                    foreach (NodeShape node in this._selectedNodes)
                    {
                        Point pt = Map.ProjToPixel(node.Geometry.Coordinates[0]);
                        e.Graphics.FillEllipse(this._nodeBrush, pt.X - this._nodeSize, pt.Y - this._nodeSize, this._nodeSize * 2, this._nodeSize * 2);


                    }
                }

                if (this._selectedVertexs != null)
                {
                    foreach (KeyValuePair<LineShape, List<int>> line in this._selectedVertexs)
                    {
                        List<Coordinate> coors = new List<Coordinate>();
                        foreach (int index in line.Value)
                        {
                            coors.Add(line.Key.Geometry.Coordinates[index]);
                        }

                        foreach (Coordinate coor in coors)
                        {
                            Point pt = Map.ProjToPixel(coor);
                            e.Graphics.FillRectangle(this._pointBrush, pt.X - this._pointSize, pt.Y - this._pointSize, this._pointSize * 2, this._pointSize * 2);
                        }
                    }
                }

                if (this._selectedLines != null)
                {
                    foreach (LineShape line in this._selectedLines)
                    {
                        List<Point> pts = new List<Point>();
                        foreach (Coordinate coor in line.Geometry.Coordinates)
                        {
                            pts.Add(Map.ProjToPixel(coor));
                        }
                        e.Graphics.DrawLines(this._linePen, pts.ToArray());
                    }
                }

                if (this._selectedPolyons != null)
                {
                    foreach (PolyShape polygon in this._selectedPolyons)
                    {
                        //有洞的多边形的绘制思路
                        //先将外围的点生成一个多边形，再生成GraphicsPath，最后生成Region
                        //将内部的多个洞生成多个多边形，再生成多个GraphicsPath，最后生成一个Region
                        //用大的Region减去（Exclude方法）小的Region,生成带洞的Region
                        //添充Region

                        List<Point> pts = new List<Point>();
                        foreach (Coordinate coor in (polygon.Geometry as Polygon).ExteriorRing.Coordinates)
                        {
                            pts.Add(Map.ProjToPixel(coor));
                        }

                        //有些多边形有洞
                        List<List<Point>> holes = new List<List<Point>>();
                        foreach (ILinearRing linearRing in (polygon.Geometry as Polygon).Holes)
                        {
                            List<Point> hole = new List<Point>();
                            foreach (Coordinate c in linearRing.Coordinates)
                            {
                                hole.Add(Map.ProjToPixel(c));
                            }
                            holes.Add(hole);
                        }

                        System.Drawing.Drawing2D.GraphicsPath path = new System.Drawing.Drawing2D.GraphicsPath();
                        path.AddPolygon(pts.ToArray());
                        Region region = new Region(path);

                        System.Drawing.Drawing2D.GraphicsPath holePath = new System.Drawing.Drawing2D.GraphicsPath();
                        foreach (List<Point> hole in holes)
                        {
                            holePath.AddPolygon(hole.ToArray());
                        }
                        Region holeRegion = new Region(holePath);

                        region.Exclude(holeRegion);

                        //e.Graphics.FillPolygon(this._polygonBrush, pts.ToArray());
                        e.Graphics.FillRegion(this._polygonBrush, region);

                    }
                }
            }
            catch (Exception ex)
            { 
            }

            base.OnDraw(e);

        }


        protected override void OnMouseDown(GeoMouseArgs e)
        {
            if (e.Clicks == 2) return;

            VectorLayer layer = this.InteractiveSystem.CurrentLayer as VectorLayer;
            if (layer == null) return;
            if (layer.Visible == false || layer.ViewMode != FMAPVIEW.NORMAL) return;

            if (this._standBy)
            {
                return;
            }

            base.OnMouseDown(e);

            if (e.Button != System.Windows.Forms.MouseButtons.Left)
            {
                return;
            }

            //鼠标位置
            this._mousePosition = e.Location;

            # region 添加顶点

            if (this._selectMode == HSelectMode.InsertVertex)
            {
                this.InsertVertex(e.GeographicLocation);
                return;
            }

            # endregion

            # region 拖拽

            if (this._selectedPts != null && this._selectedPts.Count > 0)
            {
                //鼠标作用范围
                Rectangle mouseRect = new Rectangle(_mousePosition.X - 3, _mousePosition.Y - 3, 6, 6);
                IEnvelope env = Map.PixelToProj(mouseRect).ToEnvelope();

                foreach (PointShape point in this._selectedPts)
                {
                    if (env.Contains(point.Geometry.Coordinates[0]))
                    {
                        this._dragging = true;
                        this._dragPoint = new Coordinate(point.Geometry.Coordinates[0].X, point.Geometry.Coordinates[0].Y);
                        this._startDragPoint = new Coordinate(point.Geometry.Coordinates[0].X, point.Geometry.Coordinates[0].Y);
                        this.Map.Invalidate();
                        this._dragShp = point;
                        return;
                    }
                }

            }

            if (this._selectedNodes != null && this._selectedNodes.Count > 0)
            {
                //鼠标作用范围
                Rectangle mouseRect = new Rectangle(_mousePosition.X - 3, _mousePosition.Y - 3, 6, 6);
                IEnvelope env = Map.PixelToProj(mouseRect).ToEnvelope();
                foreach (NodeShape node in this._selectedNodes)
                {

                    if (env.Contains(node.Geometry.Coordinates[0]) == true)
                    {
                        this._dragging = true;  //可移动
                        this._dragPoint = new Coordinate(node.Geometry.Coordinates[0].X, node.Geometry.Coordinates[0].Y);
                        this._startDragPoint = new Coordinate(node.Geometry.Coordinates[0].X, node.Geometry.Coordinates[0].Y);
                        this._dragShp = node;
                        this.CheckForVertexDrag();  //确定哪些点跟要移动的点有关系                        
                        Map.Invalidate();
                        return;
                    }
                }

            }

            if (this._selectedVertexs != null && this._selectedVertexs.Count > 0)
            {
                //鼠标作用范围
                Rectangle mouseRect = new Rectangle(_mousePosition.X - 3, _mousePosition.Y - 3, 6, 6);
                IEnvelope env = Map.PixelToProj(mouseRect).ToEnvelope();
                foreach (KeyValuePair<LineShape, List<int>> vertex in this._selectedVertexs)
                {
                    foreach (int i in vertex.Value)
                    {
                        if (env.Contains(vertex.Key.Geometry.Coordinates[i]) == true)
                        {
                            this._dragging = true;  //可移动
                            this._dragPoint = new Coordinate(vertex.Key.Geometry.Coordinates[i].X, vertex.Key.Geometry.Coordinates[i].Y);
                            this._startDragPoint = new Coordinate(vertex.Key.Geometry.Coordinates[0].X, vertex.Key.Geometry.Coordinates[0].Y);
                            this._dragShp = vertex.Key;
                            this._dragIndex = i;
                            this.CheckForVertexDrag();  //确定哪些点跟要移动的点有关系
                            Map.Invalidate();
                            return;
                        }
                    }
                }
            }

            # endregion


            # region 选择设置

            this._startPosition = e.Location;  //如果是框选，记下起始位置…
            this._selecting = true;
            if (this._check == false)
            {
                this._selectedNodes.Clear();
                this._selectedVertexs.Clear();
                this._selectedPts.Clear();
                this._selectedLines.Clear();
                this._selectedPolyons.Clear();
            }

            # endregion

            //Map.MapFrame.Initialize();
            //Map.Invalidate();

        }


        protected override void OnMouseMove(GeoMouseArgs e)
        {
            VectorLayer layer = this.InteractiveSystem.CurrentLayer as VectorLayer;
            if (layer == null) return;
            if (layer.Visible == false || layer.ViewMode != FMAPVIEW.NORMAL) return;

            if (this._standBy)
            {
                return;
            }


            int x = Math.Min(Math.Min(this._startPosition.X, this._mousePosition.X), e.X);
            int y = Math.Min(Math.Min(this._startPosition.Y, this._mousePosition.Y), e.Y);
            int mx = Math.Max(Math.Max(this._startPosition.X, this._mousePosition.X), e.X);
            int my = Math.Max(Math.Max(this._startPosition.Y, this._mousePosition.Y), e.Y);

            

            this._mousePosition = e.Location;

            if (this._dragging)
            {

                this._dragPoint.X = e.GeographicLocation.X;
                this._dragPoint.Y = e.GeographicLocation.Y;

                Rectangle rect = new Rectangle(this._mousePosition.X - 3, this._mousePosition.Y - 3, 6, 6);
                //IEnvelope env = this.Map.PixelToProj(rect).ToEnvelope();

                if (this._nextPoints != null && this._nextPoints.Count > 0)
                {
                    foreach (Coordinate coor in this._nextPoints)
                    {
                        Point pt = this.Map.ProjToPixel(coor);

                        Rectangle temRect = new Rectangle(Math.Min(this._mousePosition.X, pt.X), Math.Min(this._mousePosition.Y, pt.Y),
                            Math.Abs(this._mousePosition.X - pt.X), Math.Abs(this._mousePosition.Y - pt.Y));
                        rect = Rectangle.Union(rect, temRect);
                    }
                }

                rect.Inflate(20, 20);

                Map.Invalidate(rect);
                return;
            }
            //在这里判断是点选还是框选
            if (this._selecting)
            {
                this._isClick = false;

                //Rectangle rect = new Rectangle(Math.Min(this._mousePosition.X, this._startPosition.X), Math.Min(this._startPosition.Y, this._mousePosition.Y),
                //    Math.Abs(this._mousePosition.X - this._startPosition.X), Math.Abs(this._mousePosition.Y - this._startPosition.Y));

                Rectangle rect = new Rectangle(x, y, mx - x, my - y);

                rect.Inflate(30, 30);

                Map.Invalidate(rect);
            }


            base.OnMouseMove(e);
        }


        protected override void OnMouseUp(GeoMouseArgs e)
        {
            VectorLayer layer = this.InteractiveSystem.CurrentLayer as VectorLayer;
            if (layer == null) return;
            if (layer.Visible == false || layer.ViewMode != FMAPVIEW.NORMAL) return;

            if (this._standBy)
            {
                return;
            }

            base.OnMouseUp(e);

            # region 右键菜单

            if (e.Button == System.Windows.Forms.MouseButtons.Right)
            {

               

                Rectangle mouseRect;
                IEnvelope env;

                //点选范围
                mouseRect = new Rectangle(_mousePosition.X - 3, _mousePosition.Y - 3, 6, 6);
                env = Map.PixelToProj(mouseRect).ToEnvelope();

                # region 普通节点右键

                if (this._selectedPts != null && this._selectedPts.Count > 0)
                {
                    //首先判断是否显示端点右键菜单
                    bool isShowContex = false;
                    foreach (PointShape point in this._selectedPts)
                    {
                        Coordinate c = new Coordinate();
                        c = point.Geometry.Coordinates[0];

                        if (env.Contains(c))
                        {
                            isShowContex = true;
                            this._rightSelectShp = new Dictionary<string, int>();
                            this._rightSelectShp.Add(point.Id, 0);

                            break;
                        }
                        if (isShowContex == true) break;
                    }
                    //如果显示端点右键菜单，再判断是否可设置坐标
                    if (isShowContex == true)
                    {
                        bool isShowSetCoor = true;

                        //显示右键菜单

                        this._type = CONCEPTLAYERRIGHTMENU.POINT;
                        if (isShowSetCoor == true)
                        {
                            (this.InteractiveSystem.CurrentLayer as VectorLayer).IsSetCoorEffective = true;
                        }
                        else
                        {
                            (this.InteractiveSystem.CurrentLayer as VectorLayer).IsSetCoorEffective = false;
                        }
                        this._context = this.InteractiveSystem.GetConceptLayerRightClickMenu(CONCEPTLAYERRIGHTMENU.POINT);
                        this._context.Show(InteractiveSystem.GisManager.CurrentMap, e.Location);

                        return;

                    }
                }

                # endregion


                # region 线上节点右键

                if (this._selectedNodes != null && this._selectedNodes.Count > 0)
                {
                    //首先判断是否显示端点右键菜单
                    bool isShowContex = false;
                    foreach (NodeShape node in this._selectedNodes)
                    {
                        Coordinate c = new Coordinate();
                        c = node.Geometry.Coordinates[0];

                        if (env.Contains(c))
                        {
                            isShowContex = true;
                            this._rightSelectShp = new Dictionary<string, int>();
                            this._rightSelectShp.Add(node.Id, 0);  //右键设置坐标,记录

                            break;
                        }
                        if (isShowContex == true) break;
                    }
                    //如果显示端点右键菜单，再判断是否可设置坐标
                    if (isShowContex == true)
                    {
                        bool isShowSetCoor = true;

                        //显示右键菜单

                        this._type = CONCEPTLAYERRIGHTMENU.POINT;
                        if (isShowSetCoor == true)
                        {
                            (this.InteractiveSystem.CurrentLayer as VectorLayer).IsSetCoorEffective = true;
                        }
                        else
                        {
                            (this.InteractiveSystem.CurrentLayer as VectorLayer).IsSetCoorEffective = false;
                        }
                        this._context = this.InteractiveSystem.GetConceptLayerRightClickMenu(CONCEPTLAYERRIGHTMENU.NODE);
                        this._context.Show(InteractiveSystem.GisManager.CurrentMap, e.Location);

                        return;

                    }
                }

                # endregion


                # region 顶点右键

                if (this._selectedVertexs != null && this._selectedVertexs.Count > 0)
                {
                    //首先判断是否显示顶点右键菜单
                    bool isShowContex = false;
                    foreach (KeyValuePair<LineShape, List<int>> line in this._selectedVertexs)
                    {
                        Coordinate c = new Coordinate();
                        foreach (int index in line.Value)
                        {
                            c = line.Key.Geometry.Coordinates[index];                             

                            if (env.Contains(c))
                            {
                                isShowContex = true;

                                this._rightSelectShp = new Dictionary<string, int>();
                                this._rightSelectShp.Add(line.Key.Id, index);

                                break;
                            }
                        }
                        if (isShowContex == true) break;
                    }
                    //如果显示顶点右键菜单，再判断是否可设置坐标
                    if (isShowContex == true)
                    {

                        bool isShowSetCoor = true;
                        //foreach (KeyValuePair<LineShape, List<int>> line in this._selectedVertexs)
                        //{
                        //    Coordinate c = new Coordinate();
                        //    foreach (int index in line.Value)
                        //    {
                        //        c = line.Key.Geometry.Coordinates[index];
                        //        if (env.Contains(c) == false)
                        //        {
                        //            isShowSetCoor = false;
                        //            break;
                        //        }
                        //    }
                        //    if (isShowSetCoor == false) break;
                        //}

                        this._type = CONCEPTLAYERRIGHTMENU.VERTEX;
                        if (isShowSetCoor == true)
                        {
                            (this.InteractiveSystem.CurrentLayer as VectorLayer).IsSetCoorEffective = true;
                        }
                        else
                        {
                            (this.InteractiveSystem.CurrentLayer as VectorLayer).IsSetCoorEffective = false;
                        }
                        this._context = this.InteractiveSystem.GetConceptLayerRightClickMenu(CONCEPTLAYERRIGHTMENU.VERTEX);
                        this._context.Show(InteractiveSystem.GisManager.CurrentMap, e.Location);

                        return;
                    }

                }

                # endregion

                if (this._selectedLines != null)
                {
                    foreach (LineShape line in this._selectedLines)
                    {                        
                        if (( line.Geometry as LineString).Intersects(env))
                        {
                            //显示右键菜单
                            this._type = CONCEPTLAYERRIGHTMENU.LINE;
                            this._context = this.InteractiveSystem.GetConceptLayerRightClickMenu(CONCEPTLAYERRIGHTMENU.LINE);
                            this._context.Show(InteractiveSystem.GisManager.CurrentMap, e.Location);

                            return;
                        }
                    }
                }

                if (this._selectedPolyons != null)
                {
                    foreach (PolyShape polygon in this._selectedPolyons)
                    {                     
                        if ( (polygon.Geometry as Polygon).Intersects(env))
                        {
                            //显示右键菜单
                            this._type = CONCEPTLAYERRIGHTMENU.POLYGON;
                            this._context = this.InteractiveSystem.GetConceptLayerRightClickMenu(CONCEPTLAYERRIGHTMENU.POLYGON);
                            this._context.Show(InteractiveSystem.GisManager.CurrentMap, e.Location);

                            return;
                        }
                    }
                }

                return;
            }

            # endregion


            # region  图形改变事件

            if (this._dragging == true)
            {
                this._dragging = false;
                this._nextPoints = null;


                Rectangle mouseRect;
                IEnvelope env;

                //点选范围
                mouseRect = new Rectangle(this.Map.ProjToPixel(this._dragPoint).X - 3, this.Map.ProjToPixel(this._dragPoint).Y - 3, 6, 6);
                env = Map.PixelToProj(mouseRect).ToEnvelope();

                //触发图形改变的事件  

                List<string> shpIds = new List<string>();
                shpIds.Add(this._dragShp.Id);
               

                HGMSSelectMFEventArgs args;

                if (this._dragShp is LineShape)
                {
                    List<List<Coordinate>> newCoors = new List<List<Coordinate>>();
                    List<Coordinate> newCoor = new List<Coordinate>();
                    for (int i = 1; i < this._dragShp.Geometry.Coordinates.Count - 1; i++)
                    {
                        if (i == this._dragIndex)
                        {
                            newCoor.Add(this._dragPoint);
                            continue;
                        }
                        newCoor.Add(this._dragShp.Geometry.Coordinates[i]);

                    }
                    newCoors.Add(newCoor);
                    args = new HGMSSelectMFEventArgs(this.InteractiveSystem.CurrentLayer.Id, shpIds, newCoors);

                }
                else
                {
                    args = new HGMSSelectMFEventArgs(this.InteractiveSystem.CurrentLayer.Id, shpIds, new List<List<Coordinate>>() { new List<Coordinate>() { this._dragPoint } });
                }

                this.InteractiveSystem.HGMSAskEditShape(args);
                return;


                if (this._selectedPts != null && this._selectedPts.Count > 0)
                {

                    return;
                }

                if (this._selectedNodes != null && this._selectedNodes.Count > 0)
                {

                    return;
                }

                if (this._selectedVertexs != null && this._selectedVertexs.Count > 0)
                {

                    return;
                }



                Map.MapFrame.Initialize();
                Map.Invalidate();

            }

            # endregion


            # region 开始选择

            if (this._selecting == true)
            {
                this._endPosition = e.Location;  //如果是框选，记录下鼠标结束位置

                this.SelectFeature();
                //if (this._check == false)
                //{
                this._selecting = false;  //选择结束
                //}
                //选择结束，给VectorLayer赋值……
                (this.InteractiveSystem.CurrentLayer as VectorLayer).SelectedPoints = this._selectedPts;
                (this.InteractiveSystem.CurrentLayer as VectorLayer).SelectedNodes = this._selectedNodes;
                (this.InteractiveSystem.CurrentLayer as VectorLayer).SelectedVertexs = this._selectedVertexs;
                (this.InteractiveSystem.CurrentLayer as VectorLayer).SelectedLines = this._selectedLines;
                (this.InteractiveSystem.CurrentLayer as VectorLayer).SelectedPolygons = this._selectedPolyons;

            }



            # endregion

        }


        protected override void OnMouseWheel(GeoMouseArgs e)
        {
            if (this._standBy)
            {
                return;
            }

            base.OnMouseWheel(e);
        }


        protected override void OnMouseDoubleClick(GeoMouseArgs e)
        {
            //双击调属性
            base.OnMouseDoubleClick(e);

            if (this._check == true) return;  //复选模式下不让进行双击

            this._dragging = false;

            this._selectedLines = new List<LineShape>();
            this._selectedNodes = new List<NodeShape>();
            this._selectedPolyons = new List<PolyShape>();
            this._selectedPts = new List<PointShape>();


            Rectangle mouseRect = new Rectangle(_mousePosition.X - 3, _mousePosition.Y - 3, 6, 6);
            IEnvelope env = Map.PixelToProj(mouseRect).ToEnvelope();

            this._selected = false;
            this.SelectNode(env);
            if (this._selected == false)
            {
                this.SelectVertex(env);
                if (this._selected == true) return;
            }

            //this.SelectVertex(env);
            if (this._selected == false) this.SelectLine(env);
            if (this._selected == false) this.SelectPolygon(env);
            if (this._selectedLines.Count > 0 || this._selectedNodes.Count > 0 || this._selectedPolyons.Count > 0 || this._selectedPts.Count > 0)
            {
                this.InteractiveSystem.HGMSDoubleClickAttributeTable();
            }
        }


        protected override void OnKeyDown(System.Windows.Forms.KeyEventArgs e)
        {
            VectorLayer layer = this.InteractiveSystem.CurrentLayer as VectorLayer;
            if (layer == null) return;
            if (layer.Visible == false || layer.ViewMode != FMAPVIEW.NORMAL) return;

            if (this._standBy)
            {
                return;
            }

            if (e.KeyCode == System.Windows.Forms.Keys.ControlKey)
            {
                this._check = true;
            }

            if (e.KeyCode == System.Windows.Forms.Keys.Escape)
            {
                if (this._dragging)
                {
                    this._dragging = false;
                    return;
                }
                if (this._selecting == true)
                {
                    this._selecting = false;
                    return;
                }
            }

            //按delete键
            this.DeleteSelected(e);

            base.OnKeyDown(e);
        }


        protected override void OnKeyUp(System.Windows.Forms.KeyEventArgs e)
        {
            VectorLayer layer = this.InteractiveSystem.CurrentLayer as VectorLayer;
            if (layer == null) return;
            if (layer.Visible == false || layer.ViewMode != FMAPVIEW.NORMAL) return;

            if (e.KeyCode == System.Windows.Forms.Keys.ControlKey)
            {
                this._check = false;
            }

            base.OnKeyUp(e);
        }

        # endregion



        # region 辅助方法:选择、删除、显示


        /// <summary>
        /// 图形的特殊显示 保修改
        /// </summary>
        /// <param name="e"></param>
        private void DisplayFeature(MapDrawArgs e)
        {
            foreach (IFeature feature in (this.InteractiveSystem.CurrentLayer as VectorLayer).LnLayer.DataSet.Features)
            {
                System.Drawing.Point pt = Map.ProjToPixel(feature.BasicGeometry.Coordinates[0]);
                e.Graphics.FillEllipse(Brushes.Black, new Rectangle(pt.X - 4, pt.Y - 4, 8, 8));
                pt = Map.ProjToPixel(feature.BasicGeometry.Coordinates[feature.BasicGeometry.Coordinates.Count - 1]);
                e.Graphics.FillEllipse(Brushes.Black, new Rectangle(pt.X - 4, pt.Y - 4, 8, 8));

                if (this._selectMode == HSelectMode.Vertex || this._selectMode == HSelectMode.InsertVertex || this._selectMode == HSelectMode.All)
                {
                    for (int i = 1; i < feature.BasicGeometry.Coordinates.Count - 1; i++)
                    {
                        pt = Map.ProjToPixel(feature.BasicGeometry.Coordinates[i]);
                        e.Graphics.FillRectangle(Brushes.Black, new Rectangle(pt.X - 2, pt.Y - 2, 4, 4));
                    }
                }
            }
        }


        /// <summary>
        /// 根据鼠标位置选择图形
        /// </summary>
        private void SelectFeature()
        {

            //判断是点选还是框选
            if (this._startPosition.X == this._endPosition.X && this._startPosition.Y == this._endPosition.Y)
            {
                this._isClick = true;
            }         

            //鼠标作用范围
            Rectangle mouseRect;
            IEnvelope env;

            if (this._isClick == true)
            {
                //点选范围
                mouseRect = new Rectangle(_mousePosition.X - 3, _mousePosition.Y - 3, 6, 6);
                env = Map.PixelToProj(mouseRect).ToEnvelope();
            }
            else
            {
                //框选范围
                mouseRect = new Rectangle(Math.Min(this._startPosition.X, this._endPosition.X), Math.Min(this._startPosition.Y, this._endPosition.Y),
                    Math.Abs(this._startPosition.X - this._endPosition.X), Math.Abs(this._startPosition.Y - this._endPosition.Y));
                env = Map.PixelToProj(mouseRect).ToEnvelope();
            }


            //根据范围进行选择
            switch (this._selectMode)
            {
                case HSelectMode.None:

                    break;

                case HSelectMode.All:

                    //这里是根据状态的优先等级进行判断的
                    this.SelectAll(env);

                    break;
                case HSelectMode.Node:  //选择节点

                    this.SelectNode(env);

                    break;
                case HSelectMode.Vertex:  //选择顶点

                    this.SelectVertex(env);

                    break;
                case HSelectMode.Line:  //选择线,包括: 1 线图形 2 面图形的轮廓线

                    this.SelectLine(env);

                    break;
                case HSelectMode.Polygon:

                    this.SelectPolygon(env);

                    break;
                case HSelectMode.Group:
                    break;

            }
            this.Map.Invalidate();
        }


        private void SelectAll(IEnvelope env)
        {
            //现在是框选和点选 选择点（不管是端点还是顶点）统一，都是复选

            if (this._isClick == true)  //点选情况下优先选点（不管是端点还是顶点），再选线，最后选面
            {
                this._selected = false;
                this.SelectNode(env);
                if (this._selected == false) this.SelectVertex(env);
                //this.SelectVertex(env);
                if (this._selected == false) this.SelectLine(env);
                if (this._selected == false) this.SelectPolygon(env);

            }
            else //框选
            {

                this.SelectNode(env);
                //this.SelectVertex(env);
                this.SelectLine(env);
                this.SelectPolygon(env);
            }
        }


        private void SelectNode(IEnvelope env)
        {
            VectorLayer layer = this.InteractiveSystem.CurrentLayer as VectorLayer;
            if (layer == null) return;
            if (layer.Visible == false || layer.ViewMode != FMAPVIEW.NORMAL) return;


            foreach (PointShape point in this.PointShps)
            {
                if (env.Contains(point.Geometry.Coordinates[0]))
                {
                    if (this._selectedPts.Contains(point) == false)
                    {
                        this._selectedPts.Add(point);
                    }
                    if (this._isClick == true)
                    {
                        this._selected = true;
                        break;
                    }
                }
            }


            foreach (NodeShape node in this.NodeShps)
            {
                if (env.Contains(node.Geometry.Coordinates[0]))
                {
                    if (this._selectedNodes.Contains(node) == false)
                    {
                        this._selectedNodes.Add(node);
                    }
                    if (this._isClick == true)
                    {
                        this._selected = true;
                        break;
                    }
                }
            }

        }


        private void SelectVertex(IEnvelope env)
        {
            VectorLayer layer = this.InteractiveSystem.CurrentLayer as VectorLayer;
            if (layer == null) return;
            if (layer.Visible == false || layer.ViewMode != FMAPVIEW.NORMAL) return;

            foreach (LineShape line in this.LineShps)
            {
                List<int> selectedIndex = new List<int>();
                for (int i = 1; i < line.Geometry.Coordinates.Count - 1; i++)
                {
                    if (env.Contains(line.Geometry.Coordinates[i]))
                    {
                        if (selectedIndex.Contains(i) == false)
                        {
                            selectedIndex.Add(i);
                        }
                    }
                }
                if (selectedIndex.Count > 0)
                {
                    if (this._selectedVertexs.Keys.Contains(line) == false)
                    {
                        this._selectedVertexs.Add(line, selectedIndex);
                    }
                    else
                    {
                        foreach (int index in selectedIndex)
                        {
                            if (this._selectedVertexs[line].Contains(index) == false)
                            {
                                this._selectedVertexs[line].Add(index);
                            }
                        }
                    }
                    if (this._isClick == true)
                    {
                        this._selected = true;
                        break;
                    }
                }
            }
        }


        private void SelectLine(IEnvelope env)
        {
            VectorLayer layer = this.InteractiveSystem.CurrentLayer as VectorLayer;
            if (layer == null) return;
            if (layer.Visible == false || layer.ViewMode != FMAPVIEW.NORMAL) return;

            foreach (LineShape line in this.LineShps)
            {
                if (this._isClick == false)
                {
                    if (env.Contains(line.Geometry.Envelope))
                    {
                        if (this._selectedLines.Contains(line) == false)
                        {
                            this._selectedLines.Add(line);
                        }
                    }
                }
                else  //点选
                {
                    if ((line.Geometry as LineString).Intersects(env))
                    {
                        if (this._selectedLines.Contains(line) == false)
                        {
                            this._selectedLines.Add(line);
                        }
                        this._selected = true;
                        break;
                    }
                }
            }

        }


        private void SelectPolygon(IEnvelope env)
        {
            VectorLayer layer = this.InteractiveSystem.CurrentLayer as VectorLayer;
            if (layer == null) return;
            if (layer.Visible == false || layer.ViewMode != FMAPVIEW.NORMAL) return;

            foreach (PolyShape polygon in this.PolygonShps)
            {
                if (this._isClick)
                {
                    try
                    {
                        if ((polygon.Geometry as Polygon).Contains(new DotSpatial.Topology.Point(env.Center())))
                        {
                            if (this._selectedPolyons.Contains(polygon) == false)
                            {
                                this._selectedPolyons.Add(polygon);
                            }
                            this._selected = true;
                            break;
                        }
                    }
                    catch (Exception ex)
                    {

                    }
                }
                else  //框选
                {
                    try
                    {
                        if ((polygon.Geometry as Polygon).Intersects(env))
                        {
                            if (this._selectedPolyons.Contains(polygon) == false)
                            {
                                this._selectedPolyons.Add(polygon);
                            }
                        }
                    }
                    catch (Exception ex)
                    {

                    }
                }
            }

        }



        /// <summary>
        /// delete键删除图形
        /// </summary>
        /// <param name="e"></param>
        private void DeleteSelected(System.Windows.Forms.KeyEventArgs e)
        {
            if (e.KeyCode == System.Windows.Forms.Keys.Delete)
            {

                List<string> shpIds = new List<string>();
                foreach (VectorShape shp in this._selectedPts)
                {
                    shpIds.Add(shp.Id);
                }
                foreach (VectorShape shp in this._selectedPolyons)
                {
                    shpIds.Add(shp.Id);
                }
                foreach (VectorShape shp in this._selectedNodes)
                {
                    shpIds.Add(shp.Id);
                }
                foreach (VectorShape shp in this._selectedLines)
                {
                    shpIds.Add(shp.Id);
                }
                HGMSSelectMFEventArgs args;
                if (shpIds.Count > 0)
                {
                    args = new HGMSSelectMFEventArgs(this.InteractiveSystem.CurrentLayer.Id, shpIds);
                    this.InteractiveSystem.HGMSAskDeleteShape(args);
                }

                //上面是删除图形
                //下面写删除线的普通点，下来再写

                shpIds = new List<string>();

                List<string> vertexShpIds = new List<string>();
                foreach (VectorShape shp in this._selectedVertexs.Keys)
                {
                    //判断上面是否已删除 这个图形
                    if ((this.InteractiveSystem.CurrentLayer as VectorLayer).Shapes.Contains(shp) == true)
                    {
                        vertexShpIds.Add(shp.Id);
                    }
                  
                }
                if (vertexShpIds.Count > 0)
                {
                    List<List<Coordinate>> newCoors = new List<List<Coordinate>>();

                    foreach (KeyValuePair<LineShape, List<int>> shp in this._selectedVertexs)
                    {
                        if (vertexShpIds.Contains(shp.Key.Id) == false) continue;
                        List<Coordinate> newCoor = new List<Coordinate>();
                        for (int i = 1; i < shp.Key.Geometry.Coordinates.Count - 1; i++)
                        {
                            if (shp.Value.Contains(i))
                            {
                                continue;
                            }
                            newCoor.Add(shp.Key.Geometry.Coordinates[i]);

                        }
                        if (newCoor.Count <= 1 && shp.Key.Geometry.Coordinates[0].Equals(shp.Key.Geometry.Coordinates[shp.Key.Geometry.Coordinates.Count - 1]))
                        {
                            vertexShpIds.Remove(shp.Key.Id);

                            shpIds.Add(shp.Key.Id);

                        }
                        else
                        {
                            newCoors.Add(newCoor);
                        }
                    }

                    if (shpIds.Count > 0)
                    {
                        args = new HGMSSelectMFEventArgs(this.InteractiveSystem.CurrentLayer.Id, shpIds);
                        this.InteractiveSystem.HGMSAskDeleteShape(args);
                    }

                    args = new HGMSSelectMFEventArgs(this.InteractiveSystem.CurrentLayer.Id, vertexShpIds, newCoors);
                    this.InteractiveSystem.HGMSAskEditShape(args);
                }

                this._selectedPts.Clear(); // = new List<IFeature>();
                this._selectedLines.Clear();  // = new List<IFeature>();
                this._selectedNodes.Clear(); // = new Dictionary<IFeature, List<List<int>>>();
                this._selectedPolyons.Clear(); // = new List<IFeature>();
                this._selectedVertexs.Clear(); // = new Dictionary<IFeature, List<List<int>>>();

                //Map.MapFrame.Initialize();
                //Map.Invalidate();
            }
        }




        /// <summary>
        /// //确定哪些点跟要移动的点有关系
        /// </summary>
        private void CheckForVertexDrag()
        {
           
            if (this._dragPoint == null) return;            
            this._nextPoints = new List<Coordinate>();

            if (this._dragShp is PointShape)
            {
                return;
            }
            else if (this ._dragShp is NodeShape)
            {
                foreach (LineShape line in this.LineShps)
                {
                    if (line.Geometry.Coordinates[0].Equals(this._dragShp.Geometry.Coordinates[0]))
                    {
                        this._nextPoints.Add(line.Geometry.Coordinates[1]);
                    }
                    if (line.Geometry.Coordinates[line.Geometry.Coordinates.Count - 1].Equals(this._dragShp.Geometry.Coordinates[0]))
                    {
                        this._nextPoints.Add(line.Geometry.Coordinates[line.Geometry.Coordinates.Count - 2]);
                    } 
                }

            }
            else if (this._dragShp is LineShape)
            {
                for (int i = 1; i < this._dragShp.Geometry.Coordinates.Count - 1;i++ )
                {
                    if (this._dragShp.Geometry.Coordinates[i].Equals(this._dragPoint))
                    {
                        this._nextPoints.Add(this._dragShp.Geometry.Coordinates[i - 1]);
                        this._nextPoints.Add(this._dragShp.Geometry.Coordinates[i + 1]);

                        break;
                       
                    }
                }

            }
          

        }

        /// <summary>
        /// 插入顶点
        /// </summary>
        /// <param name="position"></param>
        private void InsertVertex(Coordinate position)
        {
            Rectangle rect = new Rectangle(Map.ProjToPixel(position).X - 3, Map.ProjToPixel(position).Y - 3, 6, 6);
            IEnvelope env = Map.PixelToProj(rect).ToEnvelope();

            foreach (LineShape line in this.LineShps)
            {
                if ((line.Geometry as LineString).Intersects(env) == false) continue;

                for (int i = 0; i < line.Geometry.Coordinates.Count - 1; i++)
                {
                    List<Coordinate> coorLst = new List<Coordinate>()
                    {
                        line .Geometry .Coordinates [i],
                        line .Geometry .Coordinates [i+1]
                    };

                    IFeature temFea = new Feature(FeatureType.Line, coorLst.ToArray());

                    if (temFea.Intersects(env) == false) continue;


                    List<Coordinate> newCoorLst = new List<Coordinate>();
                    newCoorLst.AddRange(line .Geometry .Coordinates .ToArray ());                    
                    newCoorLst.Insert(i + 1, new Coordinate(position.X, position.Y));
                    newCoorLst.RemoveAt(0);
                    newCoorLst.RemoveAt(newCoorLst.Count - 1);

                    HGMSSelectMFEventArgs args = new HGMSSelectMFEventArgs(this.InteractiveSystem.CurrentLayer.Id, new List<string>() { line.Id }, new List<List<Coordinate>>() { newCoorLst });

                    this.InteractiveSystem.HGMSAskEditShape(args);

                    return;

                }

            }

        }

        # endregion



        //# region 线的裁剪与合并

        ///// <summary>
        ///// 根据所选的节点切分线
        ///// </summary>
        //public void ClipFeatureByVertex()
        //{
        //    //这个方法是vertex->node的方法
        //    //即将一条线在所选的vertex处切分为两条线

        //    List<Feature> featureLst = new List<Feature>();

        //    foreach (KeyValuePair<IFeature, List<List<int>>> feature in this._selectedVertexs)
        //    {
        //        if (feature.Key.FeatureType != FeatureType.Line) continue;

        //        featureLst = new List<Feature>();
        //        //this.ClipFeature(feature, ref featureLst);
        //        featureLst = this.ClipFeature(feature);
        //        if (featureLst.Count > 1)
        //        {
        //            List<string> featureid = new List<string>();
        //            featureid.Add(feature.Key.DataRow["id"].ToString());

        //            string groupName = feature.Key.DataRow["group"].ToString();

        //            HGMSSelectMFEventArgs args = new HGMSSelectMFEventArgs(groupName, this.InteractiveSystem.CurrentLayer.Id, featureid, featureLst, false);

        //            this.InteractiveSystem.HGMSAskUnionOrSplitShape(args);
        //        }
        //    }
           
        //    this._selectedLines.Clear();  // = new List<IFeature>();
        //    this._selectedNodes.Clear(); // = new Dictionary<IFeature, List<List<int>>>();           
        //    this._selectedVertexs.Clear(); // = new Dictionary<IFeature, List<List<int>>>();

        //    Map.MapFrame.Initialize();
        //    Map.Invalidate();

        //}

        //private List<Feature> ClipFeature(KeyValuePair<IFeature, List<List<int>>> feature)
        //{
        //    List<int> index = new List<int>();
        //    for (int k = 0; k < feature.Value.Count; k++)
        //    {
        //        index.Add(feature.Value[k][1]);
        //    }
        //    //对存的坐标点的位置进行排序
        //    for (int i = 0; i < index.Count - 1; i++)
        //    {
        //        for (int j = i + 1; j < index.Count; j++)
        //        {
        //            if (index[i] > index[j])
        //            {
        //                int value = index[i];
        //                index[i] = index[j];
        //                index[j] = index[i];
        //            }
        //        }
        //    }

        //    List<Feature> featureLst = new List<Feature>();

        //    List<Coordinate> coorLst = new List<Coordinate>();
        //    Feature fea = null;

        //    for (int i = 0; i < index.Count; i++)
        //    {
        //        coorLst = new List<Coordinate>();
        //        if (i == 0)
        //        {
        //            for (int j = 0; j < index[i] + 1; j++)
        //            {
        //                coorLst.Add(feature.Key.BasicGeometry.Coordinates[j].Clone() as Coordinate);
        //            }
        //        }
        //        else
        //        {
        //            for (int j = index[i - 1]; j < index[i] + 1; j++)
        //            {
        //                coorLst.Add(feature.Key.BasicGeometry.Coordinates[j].Clone() as Coordinate);
        //            }
        //        }
        //        fea = new Feature(FeatureType.Line, coorLst.ToArray());
        //        featureLst.Add(fea);
        //    }
        //    coorLst = new List<Coordinate>();
        //    for (int j = index[index.Count - 1]; j < feature.Key.BasicGeometry.Coordinates.Count; j++)
        //    {
        //        coorLst.Add(feature.Key.BasicGeometry.Coordinates[j].Clone() as Coordinate);
        //    }
        //    fea = new Feature(FeatureType.Line, coorLst.ToArray());
        //    featureLst.Add(fea);

        //    return featureLst;
        //}


        //private void ClipFeature(KeyValuePair<IFeature, List<List<int>>> feature, ref  List<Feature> featureLst)
        //{

        //    for (int k = 0; k < feature.Value.Count; k++)
        //    {
        //        Coordinate vertex = feature.Key.BasicGeometry.Coordinates[feature.Value[k][1]];
        //        for (int i = 1; i < feature.Key.BasicGeometry.Coordinates.Count - 1; i++)
        //        {
        //            if (feature.Key.BasicGeometry.Coordinates[i].X == vertex.X && feature.Key.BasicGeometry.Coordinates[i].Y == vertex.Y)
        //            {
        //                List<List<int>> vertexs = new List<List<int>>();
        //                for (int n = k + 1; n < feature.Value.Count; n++)
        //                {
        //                    vertexs.Add(feature.Value[n]);
        //                }


        //                List<Coordinate> coorLst = new List<Coordinate>();
        //                for (int j = 0; j < i + 1; j++)
        //                {
        //                    Coordinate c = new Coordinate(feature.Key.BasicGeometry.Coordinates[j].X, feature.Key.BasicGeometry.Coordinates[j].Y);
        //                    coorLst.Add(c);
        //                }
        //                IFeature fea1 = new Feature(feature.Key.FeatureType, coorLst.ToArray());
        //                KeyValuePair<IFeature, List<List<int>>> feature1 = new KeyValuePair<IFeature, List<List<int>>>(fea1, vertexs);
        //                this.ClipFeature(feature1, ref featureLst);

        //                coorLst = new List<Coordinate>();
        //                for (int j = i; j < feature.Key.BasicGeometry.Coordinates.Count; j++)
        //                {
        //                    Coordinate c = new Coordinate(feature.Key.BasicGeometry.Coordinates[j].X, feature.Key.BasicGeometry.Coordinates[j].Y);
        //                    coorLst.Add(c);
        //                }

        //                IFeature fea2 = new Feature(feature.Key.FeatureType, coorLst.ToArray());
        //                KeyValuePair<IFeature, List<List<int>>> feature2 = new KeyValuePair<IFeature, List<List<int>>>(fea2, vertexs);
        //                this.ClipFeature(feature2, ref featureLst);

        //                return;
        //            }
        //        }

        //    }

        //    featureLst.Add(feature.Key as Feature);
        //}


        ///// <summary>
        ///// 根据所选的端点，如果两条线的端点重合，合并成一条线
        ///// </summary>
        //public void UnionFeatureByNode()
        //{
        //    //=================================================================================================================================//
        //    //下面的代码是先筛选this ._selectedNodes，因为两个端点只能是相近，不可能完全相同

        //    List<Coordinate> nodes = new List<Coordinate>();

        //    foreach (KeyValuePair<IFeature, List<List<int>>> feature in this._selectedNodes)
        //    {
        //        List<Coordinate> coors = new List<Coordinate>();
        //        foreach (List<int> ptIndex in feature.Value)
        //        {
        //            if (ptIndex[0] == 0)
        //            {
        //                coors.Add(feature.Key.BasicGeometry.Coordinates[ptIndex[1]]);
        //            }
        //            else
        //            {
        //                coors.Add((feature.Key.BasicGeometry as Polygon).Holes[ptIndex[0] - 1].Coordinates[ptIndex[1]]);
        //            }
        //        }

        //        nodes.AddRange(coors);
        //    }

        //    List<Coordinate> selectedNodes = new List<Coordinate>();
        //    List<int> index = new List<int>();
        //    for (int i = 0; i < nodes.Count - 1; i++)
        //    {
        //        Rectangle Rect = new Rectangle(this.Map.ProjToPixel(nodes[i]).X - 3, this.Map.ProjToPixel(nodes[i]).Y - 3, 6, 6);
        //        IEnvelope env = Map.PixelToProj(Rect).ToEnvelope();

        //        for (int j = i + 1; j < this._selectedNodes.Count; j++)
        //        {
        //            if (env.Contains(nodes[j]))
        //            {
        //                index.Add(j);
        //            }
        //        }
        //    }

        //    for (int i = 0; i < this._selectedNodes.Count; i++)
        //    {
        //        if (index.Contains(i) == false)
        //        {
        //            selectedNodes.Add(nodes[i]);
        //        }
        //    }

        //    this._selectedNodes.Clear(); // = new Dictionary<IFeature, List<List<int>>>();   //清空

        //    //===============================================================================================================================//

        //    List<Coordinate> usedNode = new List<Coordinate>();

        //    foreach (Coordinate node in selectedNodes)
        //    {
        //        List<string> usedId = new List<string>();

        //        if (usedNode.Contains(node)) continue;
        //        usedNode.Add(node);

        //        Rectangle Rect = new Rectangle(this.Map.ProjToPixel(node).X - 3, this.Map.ProjToPixel(node).Y - 3, 6, 6);
        //        IEnvelope env = Map.PixelToProj(Rect).ToEnvelope();

        //        List<IFeature> feas = new List<IFeature>();
        //        foreach (IFeature feature in this._selectedFeatures)
        //        {
        //            if (feature.FeatureType != FeatureType.Line) continue;

        //            if (env.Contains(feature.BasicGeometry.Coordinates[0]))
        //            {
        //                //如果是首尾相连的多边形线则不合并
        //                if (feature.BasicGeometry.Coordinates[0].X == feature.BasicGeometry.Coordinates[feature.BasicGeometry.Coordinates.Count - 1].X && feature.BasicGeometry.Coordinates[0].Y == feature.BasicGeometry.Coordinates[feature.BasicGeometry.Coordinates.Count - 1].Y)
        //                {
        //                    continue;
        //                }
        //                if (feas.Contains(feature) == false)
        //                {
        //                    usedId.Add(feature.DataRow["id"].ToString());

        //                    feas.Add(feature);
        //                    continue;
        //                }

        //            }
        //            if (env.Contains(feature.BasicGeometry.Coordinates[feature.BasicGeometry.Coordinates.Count - 1]))
        //            {
        //                if (feas.Contains(feature) == false)
        //                {
        //                    usedId.Add(feature.DataRow["id"].ToString());

        //                    feas.Add(feature);
        //                }
        //            }
        //        }

        //        //只有两个图形相连时才触发合并事件
        //        if (feas.Count == 2)
        //        {
        //            List<string> featureId = new List<string>();
        //            featureId.Add(feas[0].DataRow["id"].ToString());
        //            featureId.Add(feas[1].DataRow["id"].ToString());

        //            List<Coordinate> coorLst = new List<Coordinate>();
        //            if (env.Contains(feas[0].BasicGeometry.Coordinates[0]) && env.Contains(feas[1].BasicGeometry.Coordinates[0]))
        //            {
        //                coorLst.AddRange(feas[0].BasicGeometry.Coordinates.Reverse().ToArray());
        //                coorLst.RemoveAt(coorLst.Count - 1);
        //                coorLst.AddRange(feas[1].BasicGeometry.Coordinates.ToArray());
        //            }
        //            else if (env.Contains(feas[0].BasicGeometry.Coordinates[0]) && env.Contains(feas[1].BasicGeometry.Coordinates[feas[1].BasicGeometry.Coordinates.Count - 1]))
        //            {
        //                coorLst.AddRange(feas[1].BasicGeometry.Coordinates.ToArray());
        //                coorLst.RemoveAt(coorLst.Count - 1);
        //                coorLst.AddRange(feas[0].BasicGeometry.Coordinates.ToArray());
        //            }
        //            else if (env.Contains(feas[0].BasicGeometry.Coordinates[feas[0].BasicGeometry.Coordinates.Count - 1]) && env.Contains(feas[1].BasicGeometry.Coordinates[0]))
        //            {
        //                coorLst.AddRange(feas[0].BasicGeometry.Coordinates.ToArray());
        //                coorLst.RemoveAt(coorLst.Count - 1);
        //                coorLst.AddRange(feas[1].BasicGeometry.Coordinates.ToArray());
        //            }
        //            else if (env.Contains(feas[0].BasicGeometry.Coordinates[feas[0].BasicGeometry.Coordinates.Count - 1]) && env.Contains(feas[1].BasicGeometry.Coordinates[feas[1].BasicGeometry.Coordinates.Count - 1]))
        //            {
        //                coorLst.AddRange(feas[0].BasicGeometry.Coordinates.ToArray());
        //                coorLst.RemoveAt(coorLst.Count - 1);
        //                coorLst.AddRange(feas[1].BasicGeometry.Coordinates.Reverse().ToArray());
        //            }


        //            bool isContain = true;


        //            while (isContain == true)// this._selectedNodes.Contains(coorLst[coorLst.Count - 1]) && (usedNode.Contains(coorLst[0]) == false && usedNode.Contains(coorLst[coorLst.Count - 1]) == false))
        //            {
        //                Rectangle Rect1;
        //                IEnvelope env1 = null;

        //                isContain = false;
        //                foreach (Coordinate c in selectedNodes)
        //                {
        //                    Rect1 = new Rectangle(this.Map.ProjToPixel(c).X - 3, this.Map.ProjToPixel(c).Y - 3, 6, 6);
        //                    env1 = this.Map.PixelToProj(Rect1).ToEnvelope();
        //                    //env1.ExpandBy(3);
        //                    if (env1.Contains(coorLst[coorLst.Count - 1]))
        //                    {
        //                        usedNode.Add(c);
        //                        if (env1.Contains(coorLst[0])) break;
        //                        isContain = true;

        //                        break;
        //                    }
        //                }

        //                if (isContain == false)
        //                {
        //                    break;
        //                }



        //                List<Feature> twoFeature = new List<Feature>();

        //                foreach (IFeature feature in this._selectedFeatures)
        //                {
        //                    if (feature.FeatureType != FeatureType.Line) continue;

        //                    if (env1.Contains(feature.BasicGeometry.Coordinates[0]))
        //                    {
        //                        //如果是首尾相边的多边形线则不合并
        //                        if (feature.BasicGeometry.Coordinates[0].X == feature.BasicGeometry.Coordinates[feature.BasicGeometry.Coordinates.Count - 1].X && feature.BasicGeometry.Coordinates[0].Y == feature.BasicGeometry.Coordinates[feature.BasicGeometry.Coordinates.Count - 1].Y)
        //                        {
        //                            continue;
        //                        }
        //                        if (twoFeature.Contains(feature) == false)
        //                        {
        //                            twoFeature.Add(feature as Feature);
        //                            continue;
        //                        }

        //                    }
        //                    if (env1.Contains(feature.BasicGeometry.Coordinates[feature.BasicGeometry.Coordinates.Count - 1]))
        //                    {
        //                        if (twoFeature.Contains(feature) == false)
        //                        {
        //                            twoFeature.Add(feature as Feature);
        //                        }
        //                    }
        //                }

        //                if (twoFeature.Count != 2) break;

        //                if (usedId.Contains(twoFeature[0].DataRow["id"].ToString()))
        //                {
        //                    coorLst.RemoveAt(coorLst.Count - 1);
        //                    if (env1.Contains(twoFeature[1].BasicGeometry.Coordinates[0]))
        //                    {
        //                        coorLst.AddRange(twoFeature[1].BasicGeometry.Coordinates);
        //                    }
        //                    else
        //                    {
        //                        coorLst.AddRange(twoFeature[1].BasicGeometry.Coordinates.Reverse());
        //                    }
        //                    usedId.Add(twoFeature[1].DataRow["id"].ToString());
        //                    featureId.Add(twoFeature[1].DataRow["id"].ToString());
        //                }
        //                else
        //                {
        //                    coorLst.RemoveAt(coorLst.Count - 1);
        //                    if (env1.Contains(twoFeature[0].BasicGeometry.Coordinates[0]))
        //                    {
        //                        coorLst.AddRange(twoFeature[0].BasicGeometry.Coordinates);
        //                    }
        //                    else
        //                    {
        //                        coorLst.AddRange(twoFeature[0].BasicGeometry.Coordinates.Reverse());
        //                    }
        //                    usedId.Add(twoFeature[0].DataRow["id"].ToString());
        //                    featureId.Add(twoFeature[0].DataRow["id"].ToString());
        //                }


        //            }

        //            isContain = true;

        //            while (isContain == true) // this._selectedNodes.Contains(coorLst[0]) && (usedNode.Contains(coorLst[0]) == false && usedNode.Contains(coorLst[coorLst.Count - 1]) == false) )
        //            {
        //                Rectangle Rect1;
        //                IEnvelope env1 = null;

        //                isContain = false;
        //                foreach (Coordinate c in selectedNodes)
        //                {
        //                    Rect1 = new Rectangle(this.Map.ProjToPixel(c).X - 3, this.Map.ProjToPixel(c).Y - 3, 6, 6);
        //                    env1 = this.Map.PixelToProj(Rect1).ToEnvelope();
        //                    //env1.ExpandBy(3);
        //                    if (env1.Contains(coorLst[0]))
        //                    {
        //                        usedNode.Add(c);
        //                        if (env1.Contains(coorLst[coorLst.Count - 1])) break;
        //                        isContain = true;

        //                        break;
        //                    }
        //                }

        //                if (isContain == false)
        //                {
        //                    break;
        //                }



        //                List<Feature> twoFeature = new List<Feature>();

        //                foreach (IFeature feature in this._selectedFeatures)
        //                {
        //                    if (feature.FeatureType != FeatureType.Line) continue;

        //                    if (env1.Contains(feature.BasicGeometry.Coordinates[0]))
        //                    {
        //                        //如果是首尾相边的多边形线则不合并
        //                        if (feature.BasicGeometry.Coordinates[0].X == feature.BasicGeometry.Coordinates[feature.BasicGeometry.Coordinates.Count - 1].X && feature.BasicGeometry.Coordinates[0].Y == feature.BasicGeometry.Coordinates[feature.BasicGeometry.Coordinates.Count - 1].Y)
        //                        {
        //                            continue;
        //                        }
        //                        if (twoFeature.Contains(feature) == false)
        //                        {
        //                            twoFeature.Add(feature as Feature);
        //                            continue;
        //                        }

        //                    }
        //                    if (env1.Contains(feature.BasicGeometry.Coordinates[feature.BasicGeometry.Coordinates.Count - 1]))
        //                    {
        //                        if (twoFeature.Contains(feature) == false)
        //                        {
        //                            twoFeature.Add(feature as Feature);
        //                        }
        //                    }
        //                }

        //                if (twoFeature.Count != 2) break;

        //                if (usedId.Contains(twoFeature[0].DataRow["id"].ToString()))
        //                {
        //                    coorLst.RemoveAt(0);
        //                    if (env1.Contains(twoFeature[1].BasicGeometry.Coordinates[0]))
        //                    {
        //                        coorLst.InsertRange(0, twoFeature[1].BasicGeometry.Coordinates.Reverse());
        //                    }
        //                    else
        //                    {
        //                        coorLst.InsertRange(0, twoFeature[1].BasicGeometry.Coordinates);
        //                    }
        //                    usedId.Add(twoFeature[1].DataRow["id"].ToString());
        //                    featureId.Add(twoFeature[1].DataRow["id"].ToString());
        //                }
        //                else
        //                {
        //                    coorLst.RemoveAt(0);
        //                    if (env1.Contains(twoFeature[0].BasicGeometry.Coordinates[0]))
        //                    {
        //                        coorLst.InsertRange(0, twoFeature[0].BasicGeometry.Coordinates.Reverse());
        //                    }
        //                    else
        //                    {
        //                        coorLst.InsertRange(0, twoFeature[0].BasicGeometry.Coordinates);
        //                    }
        //                    usedId.Add(twoFeature[0].DataRow["id"].ToString());
        //                    featureId.Add(twoFeature[0].DataRow["id"].ToString());
        //                }

        //            }

        //            Feature newFea = null;

        //            Rectangle R = new Rectangle(this.Map.ProjToPixel(coorLst[0]).X - 3, this.Map.ProjToPixel(coorLst[0]).Y - 3, 6, 6);
        //            IEnvelope E = this.Map.PixelToProj(R).ToEnvelope();


        //            if (coorLst[0].X == coorLst[coorLst.Count - 1].X && coorLst[0].Y == coorLst[coorLst.Count - 1].Y)
        //            {
        //                ILinearRing linear = new LinearRing(coorLst.ToArray());
        //                newFea = new Feature(linear);
        //            }
        //            else if ((selectedNodes.Contains(coorLst[0]) || selectedNodes.Contains(coorLst[coorLst.Count - 1])) && E.Contains(coorLst[coorLst.Count - 1]))
        //            {
        //                ILinearRing linear = new LinearRing(coorLst.ToArray());
        //                newFea = new Feature(linear);
        //            }
        //            else
        //            {
        //                newFea = new Feature(feas[0].FeatureType, coorLst.ToArray());
        //            }

        //            List<Feature> features = new List<Feature>();
        //            //features.Add(feas[0] as Feature);
        //            features.Add(newFea);

        //            HGMSSelectMFEventArgs args = new HGMSSelectMFEventArgs("", this.InteractiveSystem.CurrentLayer.Id, featureId, features, true);

        //            this.InteractiveSystem.HGMSAskUnionOrSplitShape(args);
        //        }

        //    }

        //    this._selectedFeatures.Clear(); // = new List<IFeature>();
        //    this._selectedLines.Clear();  // = new List<IFeature>();
        //    this._selectedNodes.Clear(); // = new Dictionary<IFeature, List<List<int>>>();
        //    this._selectedPolygons.Clear(); // = new List<IFeature>();
        //    this._selectedVertexs.Clear(); // = new Dictionary<IFeature, List<List<int>>>();
        //}

        //# endregion
                
        //# region 多边形线转多边形的操做

        ///// <summary>
        ///// 线转多边形
        ///// </summary>
        //private void LineToPolygon()
        //{
        //    //多边形线转多边形的时候还要考虑原本就存在的多边形
        //    //思路：每转换一个多边形，遍历所有已存在的多边形，判断相互关系，添加新的，修改原来的。图层刷新

        //    foreach (IFeatureLayer layer in this.layerLst)
        //    {
        //        if (layer.DataSet.FeatureType != FeatureType.Line) continue;

        //        foreach (IFeature feature in layer.DataSet.Features)
        //        {
        //            //查找对应的自定义shp
        //            LineShape line = (this.InteractiveSystem.CurrentLayer as VectorLayer).GetShape(feature.DataRow["id"].ToString()) as LineShape;

        //            if (line.IsEnClosed == true)
        //            {
        //                bool b = (this.InteractiveSystem.CurrentLayer as VectorLayer).ExistSameKeyShp(line.PolyKey);  //判断多边形线是否已转换
        //                if (b == false)
        //                {
        //                    IFeature newPolygon = new Feature(FeatureType.Polygon, feature.BasicGeometry.Coordinates.CloneList());

        //                    //遍历所有已存在的多边形
        //                    //先判断新图形包含哪此图形，对新图形裁剪
        //                    foreach (IFeatureLayer polyLayer in this.layerLst)
        //                    {
        //                        if (polyLayer.DataSet.FeatureType != FeatureType.Polygon) continue;

        //                        //判断相互关系
        //                        foreach (IFeature polyFeature in polyLayer.DataSet.Features)
        //                        {
        //                            if (newPolygon.Contains(polyFeature))
        //                            {
        //                                newPolygon = newPolygon.Difference(polyFeature);

        //                                List<Coordinate> coorLst = new List<Coordinate>();
        //                                coorLst.AddRange((newPolygon.BasicGeometry as Polygon).ExteriorRing.Coordinates);
        //                                coorLst.RemoveAt(coorLst.Count - 1);


        //                                List<Coordinate[]> holes = new List<Coordinate[]>();
        //                                foreach (ILinearRing linear in (newPolygon as Polygon).Holes)
        //                                {
        //                                    List<Coordinate> hole = new List<Coordinate>();
        //                                    hole.AddRange(linear.Coordinates);
        //                                    hole.RemoveAt(hole.Count - 1);
        //                                    holes.Add(hole.ToArray());
        //                                }

        //                                this.InteractiveSystem.AskAddConvertedPolyShape("", line.PolyKey, coorLst.ToArray(), holes);

        //                            }
        //                        }
        //                    }

        //                    //再判断哪些图形包含新图形（裁剪后的）,再编辑旧图形
        //                    foreach (IFeatureLayer polyLayer in this.layerLst)
        //                    {
        //                        foreach (IFeature polyFeature in polyLayer.DataSet.Features)
        //                        {
        //                            if (polyFeature.Contains(newPolygon))
        //                            {
        //                                //添加新生成的
        //                                List<Coordinate> coorLst = new List<Coordinate>();
        //                                coorLst.AddRange(newPolygon.BasicGeometry.Coordinates);
        //                                coorLst.RemoveAt(coorLst.Count - 1);
        //                                this.InteractiveSystem.AskAddConvertedPolyShape("", line.PolyKey, newPolygon.BasicGeometry.Coordinates.ToArray(), null);
        //                                //修改旧的
        //                                IFeature oldFeature = polyFeature.Difference(newPolygon);

        //                                //修改事件
        //                                HGMSSelectMFEventArgs args = new HGMSSelectMFEventArgs(this.InteractiveSystem.CurrentLayer.Id, polyFeature.DataRow["id"].ToString(), oldFeature as Feature, true);
        //                                this.InteractiveSystem.HGMSAskEditShape(args);

        //                            }
        //                        }
        //                    }


        //                }
        //            }
        //        }
        //    }
        //}


        //# endregion


    }
}
